package com.hex.tcpproxy.hx;

import com.hex.tcpproxy.util.ProxyClient;
import com.hex.tcpproxy.util.ProxyHandler;

/**
 * @author: [wujie]
 * @createTime: [2019/10/10 17:22]
 * @description:
 */
public class SalveClient implements Runnable {
    private String origin;
    private String target;
    private String host;
    private Integer port;
    private MasterClient masterClient;
    private ProxyClient proxyClient;
    private ProxyHandler proxyHandler;

    public SalveClient(String origin, String target, MasterClient masterClient) {
        this.origin = origin;
        this.target = target;
        String[] split = target.split(":");
        this.host = split[0];
        this.port = Integer.parseInt(split[1]);
        this.masterClient = masterClient;
    }


    @Override
    public void run() {
        proxyHandler = new ProxyHandler() {
            @Override
            public void read(String addr, byte[] bytes) {
                masterClient.write(origin, target, bytes);
            }
        };
        proxyClient = new ProxyClient(host, port, proxyHandler);
        proxyClient.connect();
    }

    public void writeAll(byte[] bytes) {
        proxyHandler.writeAll(bytes);
    }

    public void close() {
        proxyClient.close();
    }
}
